<template>
  <div class="rightbar-wrap">
    <div class="item">
      <div class="avartar-border">
        <img @click="gotoPersonal(videoItem)" :src=" videoItem.avatar ? getImageUrl(videoItem.avatar) : logo" alt="" />
        <div
          class="addGz"
          @click="addAttention()"
          v-if="videoItem.isAttention == 0 && !videoItem.isOwn == 0"
        >
          关注
        </div>
        <div
          class="reduceGz"
          @click="addAttention()"
          v-if="videoItem.isAttention == 1 && !videoItem.isOwn == 0"
        >
          已关注
        </div>
      </div>
    </div>
    <div class="unify_size">
      <!--      点赞功能-->
      <img
        class="unify_img"
        src="../../assets/video/love.png"
        @click="addLike()"
        v-if="videoItem.isLike == 0"
      />
      <img
        class="unify_img"
        src="../../assets/video/love_red.png"
        v-if="videoItem.isLike == 1"
        @click="addLike()"
      />
      <div class="text">{{ videoItem.likeNum }}</div>
    </div>

    <div class="unify_size">
      <!--      评论-->
      <img
        class="unify_img"
        src="../../assets/video/comment.png"
        @click="toggleComment"
      />
      <div class="text">{{ videoItem.commentNum }}</div>
    </div>
    <div class="unify_size">
      <!--      收藏功能-->
      <img
        class="unify_img"
        src="../../assets/video/collect.png"
        @click="addCollecttion()"
        v-if="videoItem.isCollect == 0"
      />
      <img
        class="unify_img"
        src="../../assets/video/collect_red.png"
        @click="addCollecttion()"
        v-if="videoItem.isCollect == 1"
      />
      <div class="text">{{ videoItem.collectNum }}</div>
    </div>

    <div class="unify_size">
      <!--分享转发-->
      <img
        class="unify_img"
        src="../../assets/video/share.png"
        @click="shareLink"
        id="shareButton"
      />
      <div class="text">分享</div>
    </div>
    <van-action-sheet
      v-model="showComment"
      :title="videoItem.commentNum + '条评论'"
      style="height: 500px"
    >
      <!--      <div class="footer">-->
      <!--        <el-input placeholder="看了这么多说点什么吧" class="search" type="textarea" v-model="slclsj"-->
      <!--                  rows="2" resize="none" maxlength="200"-->
      <!--                  show-word-limit>-->
      <!--        </el-input>-->
      <!--        <div class="btn">发布</div>-->
      <!--      </div>-->
      <!--      :list="commentList"-->
      <CommentList
        ref="commentList"
        :source="videoItem.id"
        :userId="videoItem.userId"
        class="article-list"
        @update-total-count="totalCommentCount = $event"
        @reply-click="onReplyClick"
        @del-comment="handleDel"
      ></CommentList>
      <div class="article-bottom">
        <van-button
          class="comment-btn"
          type="default"
          round
          size="small"
          @click="handleClear"
          >我来说一下我的想法
        </van-button>
      </div>
    </van-action-sheet>
    <van-popup v-model="isPostShow" position="bottom" round>
      <!--      @opened="getFocus"-->
      <!-- 这里使用 v-if 的目的是让组件伴随着弹出层的显示进行渲染和销毁，防止加载过的组件不重新渲染导致数据不会重新加载的问题 🌟🌟  -->
      <PostComment
        v-if="isPostShow"
        @post-scucces="onPostSuccess"
        ref="myInput"
        :target="replyComment.id"
        :art_id="videoItem.id"
        @close="isPostShow = false"
      ></PostComment>
    </van-popup>
    <!-- /发表评论 -->

    <!-- 回复评论 -->
    <van-popup v-model="isReplyShow" position="bottom">
      <!-- 这里使用 v-if 的目的是让组件伴随着弹出层的显示进行渲染和销毁，防止加载过的组件不重新渲染导致数据不会重新加载的问题 🌟🌟  -->
      <CommentReply
        v-if="isReplyShow"
        @close="isReplyShow = false"
        :comment="replyComment"
      ></CommentReply>
    </van-popup>
  </div>
</template>

<script>
import { Toast } from "vant";
import {Dialog} from 'vant';
import "vant/lib/icon/local.css";
import CommentList from "../../views/share/components/comment-list";
import CommentReply from "../../views/share/components/comment-reply";
import PostComment from "../../views/share/components/post-comment";
import { mapState } from "vuex";
import { addAuthorLike, addCollect, updateLikes,deleteComment } from "../../api/share";
import { mapMutations } from "vuex";
import store from '../../store'
import {antiShake} from '@/utils/antie.js'//防抖函数
export default {
  name: "RightBar",
  components: {
    CommentList,
    CommentReply,
    PostComment,
  },
  props: {
    myArray: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      store:store,
      totalCommentCount: 0, // 评论数量
      replyComment: {}, //  当前回复评论对象
      isReplyShow: false, //控制回复评论弹出层的状态
      isPostShow: false,
      total: "1190条评论",
      isPublish: false,
      content: "",
      logo: require("@/assets/tx.png"),
      showCommentBox: false,
      comment: "",
      showShare: false,
      options: [
        { name: "微信", icon: "wechat", openType: "share" },
        { name: "QQ", icon: "qq", openType: "share" },
        { name: "微博", icon: "weibo" },
        { name: "复制链接", icon: "link" },
      ],
      commentNum: 3,
      showComment: false,
      keyword: "",
      favorites: false,
      likes: false,
      gz: false,
      reply:false,
    };
  },
  computed: {
    ...mapState("share", ["videoItem"]),
  },
  mounted() {
    window["getInfoFromFlutter"] = (info) => {
      if (JSON.parse(info).action === "share") {
        this.getInfoFromFlutter(info);
      }
    };
    console.log("rightBar videoItem", this.videoItem);
  },
  watch: {
    videoItem: {
      handler(newVal, oldVal) {
        if (newVal != oldVal) {
          console.log("videoItem.id变化", newVal.id);
        }
      },
    },
    // 'showComment': {
    //   handler(newVal, oldVal) {
    //     if (newVal == true && newVal != oldVal) {
    //       this.$nextTick(() => {
    //         this.commentList = []
    //       })
    //     }
    //   }
    // },
    // "videoItem.isAttention": {
    //   handler(newChats, oldChats) {
    //     if (newChats == 1) {
    //       this.gz = true;
    //     } else {
    //       this.gz = false;
    //     }
    //     this.$forceUpdate();
    //     console.log("watch likes", this.likes);
    //   },
    //   deep: true,
    // },
    // "videoItem.isLike": {
    //   handler(newChats, oldChats) {
    //     if (newChats == 1) {
    //       this.likes = false;
    //     } else {
    //       this.likes = true;
    //     }
    //     this.$forceUpdate();
    //     console.log("watch likes", this.likes);
    //   },
    //   deep: true,
    // },
    // "videoItem.isCollect": {
    //   handler(newVal, oldVal) {
    //     if (newVal == 0) {
    //       this.favorites = true;
    //     } else {
    //       this.favorites = false;
    //     }
    //     this.$forceUpdate();
    //     console.log("watch favorites", this.favorites);
    //   },
    //   deep: true,
    // },
  },
  methods: {
    ...mapMutations("share", [
      "addLikesNum",
      "reduceLikesNum",
      "addCollectNum",
      "reduceCollectNum",
    ]),
    getImageUrl(img) {
      return `${store.state.imgUrl}` + img;
    },
    topFn() {
      // 建议：用原生的js，因为js代码是在html+css运行后，真实的DOM已经在网页上来，从document往下获取标签是ok的
      // 这种方法既可以实现滚动，也有动画效果
      // scrollIntoView(), 让原生的标签滚动到屏幕的最上面
      this.$nextTick(() => {
        document.querySelector(".article-list").scrollIntoView({
          behavior: "smooth",
        });
      });
    },
    // 打开弹窗 —— 自动获取焦点，立刻滚动到第一条评论
    getFocus() {
      // 获得焦点后，自动滚动到第一条滚动条
      this.topFn();
    },
    // 回复评论
    onReplyClick(comment) {
      // console.log('onReplyClick', components)
      // 获取当前评论
      this.reply = false
      this.replyComment = comment;
      console.log("打印当前评论", comment, comment.id);
      // 打开回复评论弹窗
      this.isPostShow = true;
      this.videoItem.commentNum += 1;
    },
    // 对文章评论
    onPostSuccess(comment) {
      const commentNew = comment
      if (this.reply) {
        commentNew.reply = ''
      }
      //移到store中去修改数据
      this.$store.commit("share/UPDATE_COMMENT_LIST", commentNew);
      // 更新评论的数量
      this.totalCommentCount++;
      // 关闭发布评论弹出层
      this.isPostShow = false;
    },
    handleClear(){
        this.isPostShow = true
        this.reply = true
        this.replyComment.id = ''
    },
    showTextarea() {
      this.isPublish = !this.isPublish;
    },
    sendMessage() {
      this.$emit("send-message", this.keyword);
      this.keyword = "";
    },
    onSelect(option) {
      Toast(option.name);
      if (option.name === "微信") {
        window.location.href = "weixin://";
      } else if (option.name === "qq") {
        //跳转qq链接
      } else if (option.name === "微博") {
        //跳转微博的链接
      } else if (option.name === "复制链接") {
        //复制链接
        this.copyLink();
      }
      this.showShare = false;
    },
    copyLink() {
      const link = window.location.href; // 要复制的链接
      // console.log(link)
      // 使用Vant的Clipboard组件的copy方法复制链接
      // this.$vant.Clipboard.copy(link)
      //   .then(() => {
      //     this.$toast('链接已复制'); // 复制成功提示
      //   })
      //   .catch(() => {
      //     this.$toast('复制失败'); // 复制失败提示
      //   });
      let inputNode = document.createElement("input"); // 创建input
      inputNode.value = link; // 赋值给 input 值
      document.body.appendChild(inputNode); // 插入进去
      inputNode.select(); // 选择对象
      document.execCommand("Copy"); // 原生调用执行浏览器复制命令
      inputNode.className = "oInput";
      inputNode.style.display = "none"; // 隐藏
      this.$toast.success("复制成功");
    },
    async toggleComment() {
      this.showComment = true;
      this.$nextTick(() => {
        this.$refs.commentList.init();
      });
    },
    addCollecttion: antiShake( async function (item){
      let res = await this.gotoCollection();
      // if (res.code == 0) {
        if (this.videoItem.isCollect == 0) {
           this.$toast.success("收藏成功");
           this.videoItem.isCollect = 1;
           this.addCollectNum();
        }else if (this.videoItem.isCollect == 1) {
           this.$toast.success("取消收藏");
           this.videoItem.isCollect = 0;
           this.reduceCollectNum();
        }
       
      // }
    }),
    // async reduceCollection() {
    //   let res = await this.gotoCollection();
    //   // if (res.code == 0) {
    //     this.$toast.success("取消收藏");
    //     this.videoItem.isCollect = 0;
    //     this.reduceCollectNum();
    //   // }
    // },
    //取消点赞
    // async reduceLike() {
    //   let res = await this.gotoLikes();
    //   // if (res.code == 0) {
    //     this.$toast.success("取消点赞");
    //     this.videoItem.isLike = 0;
    //     this.reduceLikesNum();
    //   // }
    // },
    //关注
    addAttention: antiShake( async function (){
      // let res = await this.getAttention();
      // if (res.code == 0) {
        if (this.videoItem.isAttention == 0) {
          let res = await this.getAttention()
          this.$toast.success("关注成功");
          this.videoItem.isAttention = 1;
        }else if (this.videoItem.isAttention == 1) {
          this.tipIsAttention()
           
        }
        
      // }
    }),
    //取消关注提示
    tipIsAttention(){
      Dialog.confirm({
        title: '提示',
        message: '您确定要取消关注该用户吗？',
        confirmButtonColor: 'rgba(242, 150, 0, 1)'
      }).then(() => {
          this.getAttention()
          this.$toast.success("取关成功");
          this.videoItem.isAttention = 0;
      }).catch(err => {
        
      })
    }, 
    // async reduceAttention() {
    //   let res = await this.getAttention();
    //   // if (res.code == 0) {
    //     this.$toast.success("取关成功");
    //     this.videoItem.isAttetion = 0;
    //   // }
    // },
    getAttention() {
      let data = {
        id: this.videoItem.userId,
      };
      return new Promise((resolve, reject) => {
        addAuthorLike(data).then((res) => {
          resolve(res);
        });
      });
    },
    //点赞/取消点赞
    addLike: antiShake( async function () {
      console.log("打印this.likes", this.likes);
      let res = await this.gotoLikes();
      if (res.code == 0) {
        if (this.videoItem.isLike == 0) {
           this.$toast.success("点赞成功");
           this.videoItem.isLike = 1;
           this.addLikesNum();
        }else if (this.videoItem.isLike == 1) {
          this.$toast.success("取消点赞");
          this.videoItem.isLike = 0;
          this.reduceLikesNum();
        }
       
      }
    }),
    gotoCollection() {
      let data = {
        id: this.videoItem.id,
        type: 0, //文章，动态，视频是0 评论是1
      };
      return new Promise((resolve, reject) => {
        addCollect(data).then((res) => {
          resolve(res);
        });
      });
    },
    gotoLikes() {
      let data = {
        id: this.videoItem.id,
        type: 0, //文章，动态，视频是0 评论是1
      };
      return new Promise((resolve, reject) => {
        updateLikes(data).then((res) => {
          resolve(res);
        });
      });
    },
    toggleGz() {
      this.gz = !this.gz;
    },
    shareLink(item) {
      // console.log('点击分享按钮')
      // this.showShare = true
      let message = {
        action: "share",
        param: {
          type: "link", //必填
          title: item.title, //必填
          name: "/home/page",
          subtitle: item.description,
          link: "http://192.168.110.105:9033/#/page?" + item.id, //动态列表的详情?id:''
          callback: 1,
        },
      };
      // console.log(message)
      getInfoFromVue.postMessage(JSON.stringify(message));
    },
    submitComment() {
      // 提交评论的实现
      this.$store.dispatch("addComment", this.comment);
      this.comment = "";
    },
    getInfoFromFlutter(info) {
      let data = JSON.parse(info);
      if (data.param.succeed == 1) {
        this.$toast.success("分享成功");
      } else {
        this.$toast.fail("已取消分享");
      }
    },
     //删除评论
    handleDel(comment){
      this.$store.commit('share/DELETE_COMMENT_LIST', comment)
      
      if (comment.children.length > 0) {//如果子集有评论则删除数量应该加上子集数量
        this.totalCommentCount -= 1 + comment.children.length
      }else{
         this.totalCommentCount -= 1
      }
      deleteComment(comment.id).then((res) => {
        if (res.code === 0) {
          this.$toast('已删除该评论')
        }
      }).catch((err) => {
        this.$toast('评论删除失败')
      })
    },
    // 跳转到主页
    gotoPersonal(item) {
      if (item.isOwn == 0) {//跳转到自己的个人主页
        this.$router.push({path: '/personalPage',query:{}})
      }else{//跳转到别人主页的个人主页
        this.$router.push({path: '/visitPersonal',query:{obj:JSON.stringify(item)}})
      }
    }
  },
};
</script>

<style lang="less" scoped>
.rightbar-wrap {
  z-index: 999;
  position: fixed;
  bottom: 20%;
  right: 5px;
  //height: 200px;
  width: 15%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  /deep/ .van-share-sheet__cancel {
    color: #646566;
  }

  .item {
    padding-bottom: 25px;

    .avartar-border {
      position: relative;
      width: 50px;
      height: 50px;
      border: 1px solid #fff;
      border-radius: 50%;

      .addGz {
        width: 41px;
        height: 17px;
        opacity: 1;
        border-radius: 3px;
        background: rgba(242, 150, 0, 1);
        font-size: 12px;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
        text-align: center;
        position: absolute;
        bottom: -20%;
        right: 5%;
      }

      .reduceGz {
        text-align: center;
        font-size: 12px;
        font-weight: 400;
        width: 41px;
        height: 17px;
        opacity: 1;
        border-radius: 3px;
        background: rgba(250, 250, 250, 1);
        line-height: 17.38px;
        color: rgba(199, 199, 199, 1);
        position: absolute;
        bottom: -20%;
        right: 5%;
      }

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }

      .icon-add1 {
        position: absolute;
        bottom: -42%;
        left: 50%;
        transform: translate(-50%, 0%);
        color: #ff4161;
        font-size: 24px;
      }
    }
  }

  .unify_size {
    //margin-left: 8px;
    margin-top: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    //.icon {
    //  display: inline-block;
    //  width: 30px;
    //  height: 30px;
    //  background-image: url('../../assets/video/love.png'); /* 替换为你自己的图标路径 */
    //  background-size: cover;
    //  transition: transform 0.3s ease-in-out;
    //}

    .text {
      margin-top: 3px;
      display: inline-block;
      transition: color 0.3s ease-in-out;
    }

    //.favorite-button.active .icon {
    //  transform: scale(1.2);
    //  background-image: url('../../assets/video/love_red.png'); /* 替换为你自己的图标路径 */
    //}

    .unify_img {
      width: 24px;
      height: 24px;
    }

    .text {
      color: #fff;
      font-size: 13px;
      //margin-left: 15px;
      //margin-top: 6px;
    }
  }

  /deep/ .van-action-sheet__content {
    overflow-y: scroll;
    padding-bottom: 44px;
  }

  .article-bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 44px;
    background: #fff;
    //border-top: 1px solid #d8d8d8;
    display: flex;
    justify-content: center;
    align-items: center;
    // 按钮
    .comment-btn {
      width: 357px;
      height: 30px;
      font-size: 15px;
      color: #a7a7a7;
      border-radius: 15px;
      border: solid 1px #eeeeee;
      background: rgba(229, 229, 229, 1);
    }

    .content {
      height: 400px;
      padding: 8px;
      font-size: 13px;
    }
  }
}
</style>
